// 首页
import React, { lazy, Suspense } from "react";
import { useNavigate, useLocation } from 'react-router-dom';
import { useDeviceType } from '@/utils/deviceDetection';

// 懒加载组件 - 减少首屏JavaScript包大小
const Cards = lazy(() => import("./components/cards/Cards"));
const SearchInput = lazy(() => import("./components/searchInput/searchInput"));
const InformationCard = lazy(() => import("./components/informationCard/InformationCard"));

// 加载占位组件
const ComponentFallback = () => (
  <div className="flex items-center justify-center p-4">
    <div className="loading-skeleton w-full h-32 rounded-lg"></div>
  </div>
);

const homePage: React.FC = () => {
  // 设备类型检测
  const deviceType = useDeviceType();
  const location = useLocation();
  const [infoVisible, setInfoVisible] = React.useState<boolean>(false); // 信息弹窗是否显示
  const [infoCard, setInfoCard] = React.useState<any | null>(null); // 信息弹窗卡片数据

  // 筛选条件（来自 Header 的移动端筛选弹窗）：race/category/origin/keyword
  const [filters, setFilters] = React.useState<{ keyword?: string; race?: string; category?: string; origin?: string } | null>(() => {
    try {
      const saved = sessionStorage.getItem('home_filters_state');
      return saved ? JSON.parse(saved) : null;
    } catch {
      return null;
    }
  });

  // 仅保留必要的状态持久化标识（如需）
  const isRestoringStateRef = React.useRef<boolean>(false);

  // displayMode 初始化：从 sessionStorage 恢复或默认 'explore'
  const [displayMode, setDisplayMode] = React.useState<'explore' | 'list'>(() => {
    try {
      const saved = sessionStorage.getItem('home_display_mode');
      return (saved as 'explore' | 'list') || 'explore';
    } catch {
      return 'explore';
    }
  });

  const isListMode = displayMode === 'list';

  // 增强的数据持久化：保存完整状态到 sessionStorage
  const saveStateToStorage = React.useCallback((newFilters?: any) => {
    try {
      // 保存筛选条件
      if (newFilters !== undefined) {
        sessionStorage.setItem('home_filters_state', JSON.stringify(newFilters));
      }
      // 保存 displayMode
      try {
        sessionStorage.setItem('home_display_mode', displayMode);
      } catch { }

      // 保存页面状态（仅记录时间与路径）
      const currentState = {
        timestamp: Date.now(),
        location: location.pathname
      };
      sessionStorage.setItem('home_page_state', JSON.stringify(currentState));
    } catch (e) {
      console.warn('Failed to save home state:', e);
    }
  }, [location.pathname]);

  // 根据 displayMode 决定容器高度
  const containerStyle = React.useMemo<React.CSSProperties>(() => {
    const base: React.CSSProperties = { minHeight: 'var(--content-h)' };
    if (!isListMode) {
      base.height = 'var(--content-h)';
    }
    return base;
  }, [isListMode]);

  // 页面离开时保存状态
  React.useEffect(() => {
    const handleBeforeUnload = () => {
      // 保存当前状态（filters）
      saveStateToStorage(filters);
    };

    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        // 页面变为不可见时保存状态
        saveStateToStorage(filters);
      }
    };

    // 监听页面卸载和可见性变化
    window.addEventListener('beforeunload', handleBeforeUnload);
    document.addEventListener('visibilitychange', handleVisibilityChange);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    };
  }, [saveStateToStorage, filters]);

  // 监听筛选条件变化事件（来自 Header 的移动端筛选弹窗）
  React.useEffect(() => {
    const handleFiltersApply = (e: CustomEvent) => {
      const newFilters = e.detail;
      setFilters(newFilters);
      saveStateToStorage(newFilters);
    };

    const handleFiltersReset = () => {
      setFilters(null);
      saveStateToStorage(null);
    };

    window.addEventListener('home_filters_apply', handleFiltersApply as EventListener);
    window.addEventListener('home_filters_reset', handleFiltersReset);

    return () => {
      window.removeEventListener('home_filters_apply', handleFiltersApply as EventListener);
      window.removeEventListener('home_filters_reset', handleFiltersReset);
    };
  }, [saveStateToStorage]);

  // 监听搜索结果事件（如有需要可转为通知子组件，暂时仅保存查询词）
  React.useEffect(() => {
    const handleSearchResults = (e: any) => {
      try {
        const detail = e?.detail;
        if (!detail) return;
        const { results } = detail;
        if (Array.isArray(results)) {
          // 将结果交由子组件内部逻辑处理，这里不再直接写入 items
          // 可根据需要仅持久化过滤条件
          saveStateToStorage(filters);
        }
      } catch { }
    };
    window.addEventListener('home_search_results', handleSearchResults as any);
    return () => { window.removeEventListener('home_search_results', handleSearchResults as any); };
  }, [filters, saveStateToStorage]);

  // 点击卡片时调用
  const handleCardClick = React.useCallback((card: any) => {
    setInfoCard(card);
    setInfoVisible(true);
  }, []);

  // 导航 hook：用于响应来自 message card 的导航事件
  const navigate = useNavigate();

  // 监听来自 MobileTabBar 的导航前状态保存事件
  React.useEffect(() => {
    const handleSaveStateBeforeNavigate = (e: any) => {
      try {
        const targetPath = e?.detail?.targetPath;
        if (targetPath) {
          // 立即保存当前状态
          saveStateToStorage(filters);
        }
      } catch (e) {
        // 忽略错误
      }
    };

    window.addEventListener('home_save_state_before_navigate', handleSaveStateBeforeNavigate);
    return () => {
      window.removeEventListener('home_save_state_before_navigate', handleSaveStateBeforeNavigate);
    };
  }, [filters, saveStateToStorage]);

  // 监听来自 message card 的导航事件（由 photo_messagecard 触发）
  React.useEffect(() => {
    const handler = (e: any) => {
      try {
        const d = e?.detail;
        if (!d) return;
        navigate('/CreateImage', { state: { id: d.id, name: d.name, image_url: d.image_url, role_prompt: d.role_prompt, category: d?.category } });
      } catch { }
    };
    window.addEventListener('navigate_to_create_image', handler as any);
    return () => { try { window.removeEventListener('navigate_to_create_image', handler as any); } catch { } };
  }, [navigate]);

  return (
    <div style={containerStyle} className='w-full border mt-4'>
      {/* PC端搜索输入框 */}
      {deviceType === 'pc' && (
        <Suspense fallback={<ComponentFallback />}>
          <SearchInput />
        </Suspense>
      )}

      {/* 主要内容区域 - 只显示Cards组件 */}
      <Suspense fallback={<ComponentFallback />}>
        <Cards filters={filters} onCardClick={handleCardClick} />
      </Suspense>

      {/* 信息弹窗 */}
      {infoVisible && infoCard && (
        <Suspense fallback={<ComponentFallback />}>
          <InformationCard
            visible={infoVisible}
            card={infoCard}
            onClose={() => {
              setInfoVisible(false);
              setInfoCard(null);
            }}
          />
        </Suspense>
      )}
    </div>
  );
};


export default homePage;
